package com.HospitalOutpatient.controller.interceptor;

import com.HospitalOutpatient.annotation.LoginToken;
import com.HospitalOutpatient.controller.Code;
import com.HospitalOutpatient.controller.DoctorContext;
import com.HospitalOutpatient.controller.UserContext;
import com.HospitalOutpatient.dao.DoctorDao;
import com.HospitalOutpatient.entity.Doctor;
import com.HospitalOutpatient.entity.User;
import com.HospitalOutpatient.exception.NotLoginException;
import com.HospitalOutpatient.service.UserService;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Slf4j
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;

    @Autowired
    private DoctorDao doctorDao;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 获取请求头中的 token
        String token = request.getHeader("Authorization");
        // 如果不是映射到方法的，直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        // 获取请求的方法
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        // 验证是否存在需要验证用户权限的注释
        if (method.isAnnotationPresent(LoginToken.class)) {
            if (method.getAnnotation(LoginToken.class).required()) {
                // 执行认证
                if (token == null) {
                    log.error("token 不存在，请重新登录");
                    throw new NotLoginException("token 不存在 请重新登录", Code.LOGIN_ERR);
                }
                // 获取 userId
                String userId;
                try {
                    userId = JWT.decode(token).getAudience().get(0);
                } catch (JWTDecodeException e) {
                    log.error("token 解码失败");
                    throw new NotLoginException("token 解码失败 请重新登录", Code.LOGIN_ERR);
                }
                // 根据 userId 查询 User
                User user = userService.getUserById(userId);
                if (user == null) {
                    log.error("用户不存在，请重新登录");
                    throw new NotLoginException("用户不存在 请重新登录", Code.LOGIN_ERR);
                }
                // 验证 token
                JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassWord())).build();
                try {
                    jwtVerifier.verify(token);
                } catch (JWTVerificationException e) {
                    log.error("token 校验失败");
                    throw new NotLoginException("token 校验失败 请重新登录", Code.LOGIN_ERR);
                }
                if(user.getIdentity().equals("2")){
                    Doctor doctor = doctorDao.selectDoctorByUserId(userId);
                    DoctorContext.set(doctor);
                }
                UserContext.set(user);
                return true;
            }
        }
        return true;
    }
}

